package com.meitianhui.convenitenbuy.module.order.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.home.ui.activity.web.AdWebViewActivity;
import com.meitianhui.convenitenbuy.module.order.model.bean.OrderInfo;
import com.meitianhui.convenitenbuy.util.DateUtil;
import com.meitianhui.convenitenbuy.util.EmptyUtil;
import com.meitianhui.convenitenbuy.util.GlideUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.StringUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by amy on 2018/1/13.
 */

public class HuiGuoOrderAdapterTest extends BaseQuickAdapter<OrderInfo.ListBean, BaseViewHolder> {
    private Context mContext;
    private Map<String, String> mUrlMap;
    private OnClickOrder mOnClickOrder;
    private HashMap<String, CountDownTimer> countDownMap;
    private String status;
    String path_id = "";

    public HuiGuoOrderAdapterTest(Context context, List<OrderInfo.ListBean> data, Map<String, String> urlMap, OnClickOrder onClickOrder) {
        super(R.layout.item_huiguo_order, data);
        mContext = context;
        mUrlMap = urlMap;
        mOnClickOrder = onClickOrder;
        countDownMap = new HashMap<String, CountDownTimer>();
    }

    /**
     * 清空资源
     */
    public void cancelAllTimers() {
        if (countDownMap == null) {
            return;
        }

        for (CountDownTimer timer : countDownMap.values())
            if (timer != null) {
                timer.cancel();
            }
    }

    @Override
    protected void convert(BaseViewHolder helper, OrderInfo.ListBean item) {

        ImageView ivGood = helper.getView(R.id.iv_good);  //商品图片
        TextView mTvSubmitType = helper.getView(R.id.tv_submit_type);
        //订单类型
        if (TextUtils.equals(item.getOrder_type(), "huiguo")) {
            //会过的标签
            mTvSubmitType.setBackgroundResource(R.drawable.will_self_text_bg);
            mTvSubmitType.setTextColor(mContext.getResources().getColor(R.color.homeWillText));
            mTvSubmitType.setText("会过");
        } else {
            //自营的标签
            mTvSubmitType.setBackgroundResource(R.drawable.edinburgh_self_text_bg);
            mTvSubmitType.setTextColor(mContext.getResources().getColor(R.color.homeEdinburghSelfText));
            mTvSubmitType.setText("自营");
        }
        //商品名称
        helper.setText(R.id.tv_submit_title, item.getItem_goods_title());
        // 商品SKU_ID
        if (EmptyUtil.isEmpty(item.getSku_id())) {
            helper.setVisible(R.id.tv_submit_attrs, false);
        } else {
            String attrs;
            String zValue = item.getAttr_zvalue();
            String fValue = item.getAttr_fvalue();
            if (EmptyUtil.isEmpty(zValue)) {
                attrs = "";
            } else {
                attrs = item.getProp_zname() + ":" + zValue;
                attrs = EmptyUtil.isEmpty(fValue) ?
                        attrs : attrs + "   " + item.getProp_fname() + ":" + fValue;
            }
            helper.setText(R.id.tv_submit_attrs, attrs);
        }
        // 商品数量
        String qty = EmptyUtil.isEmpty(item.getQty()) ? "1" : item.getQty();
        helper.setText(R.id.tv_submit_number, "x" + qty);
        // 商品价格
        String saleFee = StringUtils.moneyMul(item.getSale_fee(), qty);     // 商品价格
        String totalFee = StringUtils.moneyMul(item.getTotal_fee(), qty);   // 返还金额
        helper.setText(R.id.tv_submit_money, "总预付金额: ¥" + saleFee + " (返¥" + totalFee + ")");

        RelativeLayout rlBig = helper.getView(R.id.rl_big_layout);  //下面按钮的大布局
        //订单编号
        helper.setText(R.id.tv_huiguo_order_number, item.getOrder_no());
        helper.setText(R.id.tv_huiguo_create_date, item.getOrder_date());  //时间
        helper.setText(R.id.tv_huiguo_contact_person, item.getContact_person());  //联系人
        helper.setText(R.id.tv_huiguo_address_phone, item.getContact_tel());
        helper.setIsRecyclable(false);
        //倒计时的时间
        TextView tvMin = helper.getView(R.id.tv_min);  //分钟
        TextView tvSecond = helper.getView(R.id.tv_sec);  //秒钟
        RelativeLayout rlPayment = helper.getView(R.id.rl_payment);  //前去付款
        //最后一排订单操作按钮
        //查看物流
        Button btnLogistics = helper.getView(R.id.btn_logistics_message);
        //取消订单
        Button btnCancleOrder = helper.getView(R.id.btn_cancle_order);
        //确认订单
        Button btnConfirmOrder = helper.getView(R.id.btn_confirm_order);
        //联系客服
        Button btnCustomerService = helper.getView(R.id.btn_customer_service);
        //物流信息
        TextView tvLogisticsMessage = helper.getView(R.id.tv_huiguo_logistics_message);

        LinearLayout llLogisticsMessage = helper.getView(R.id.ll_logistics_message);  //


        try {
            JSONArray jsonArray = new JSONArray(item.getItem_goods_pic_info());
            path_id = jsonArray.getJSONObject(0).getString("path_id");
        } catch (Exception e) {
            e.printStackTrace();
        }
        GlideUtils.setCircleImage(mContext, mUrlMap.get(path_id), R.mipmap.wallet_coupon_item_default, R.mipmap.wallet_coupon_item_default, ivGood);
        //订单状态
        status = item.getStatus();
        if (!TextUtils.isEmpty(status)) {
            if (status.equals(Constants.PC__ORDER_PROCESSING)) {    /**处理中**/
                helper.setText(R.id.tv_status, "已预定");
                rlPayment.setVisibility(View.VISIBLE);
                btnCancleOrder.setVisibility(View.VISIBLE);
                btnLogistics.setVisibility(View.GONE);
                btnConfirmOrder.setVisibility(View.GONE);
                btnCustomerService.setVisibility(View.GONE);

                //点击取消订单
                btnCancleOrder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mOnClickOrder.cancelClick(item.getOrder_id());
                    }
                });
                //点击前去付款
                rlPayment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        HashMap<String, String> map = new HashMap<>();
                        map.put("amount", item.getSale_fee());
                        map.put("title", item.getItem_goods_title());
                        map.put("goods_code", item.getItem_goods_code());
                        map.put("thumb_pic", mUrlMap.get(path_id));
                        map.put("discount_price", item.getDiscount_fee());
                        map.put("quantity", item.getQty());

                        if (TextUtils.equals(item.getOrder_type(), "huiguo")) {
                            //会过的标签
                            map.put("data_source", "huiguo");
                        } else {
                            //自营的标签
                            map.put("data_source", "meitianhui");
                        }
                        String value = new Gson().toJson(map);

                        mOnClickOrder.goToSubmitOrder(value,item.getOrder_id());
                    }
                });

            } else if (status.equals(Constants.PC__ORDER_CONFIRMED)) {  /**已下单(48小时)**/
                helper.setText(R.id.tv_status, "已下单");
                rlPayment.setVisibility(View.GONE);
                btnLogistics.setVisibility(View.GONE);
                btnConfirmOrder.setVisibility(View.GONE);
                btnCancleOrder.setVisibility(View.GONE);
                rlBig.setVisibility(View.GONE);
                String orderdate = item.getOrder_date();
                String s_date = DateUtil.getDistanceToNow(orderdate);
                if ("timeout".equals(s_date)) {
                    btnCustomerService.setVisibility(View.VISIBLE);
                    //联系客服
                    btnCustomerService.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mOnClickOrder.customerClick();
                        }
                    });
                } else {
                    btnCustomerService.setVisibility(View.GONE);
                }

            } else if (status.equals(Constants.PC_ORDER_DELIVERED)) {  /**已发货**/
                helper.setText(R.id.tv_status, "已发货");
                rlBig.setVisibility(View.GONE);
            } else if (status.equals(Constants.PC__ORDER_PAYED)) {    /**已支付**/
                helper.setText(R.id.tv_status, "已支付");
                rlBig.setVisibility(View.GONE);
            } else if (status.equals(Constants.PC__ORDER_RECEIVED)) {  /**已收货**/
                helper.setText(R.id.tv_status, "已收货");
                rlBig.setVisibility(View.GONE);
            } else if (status.equals(Constants.PC__ORDER_CLOSED)) {   /**已返款**/
                helper.setText(R.id.tv_status, "已返款");
                llLogisticsMessage.setVisibility(View.VISIBLE);
                rlPayment.setVisibility(View.GONE);
                btnLogistics.setVisibility(View.VISIBLE);
                btnConfirmOrder.setVisibility(View.GONE);
                btnCustomerService.setVisibility(View.GONE);
                btnCancleOrder.setVisibility(View.GONE);
                String logistics = item.getLogistics();
                if (!TextUtils.isEmpty(logistics)) {
                    try {
                        JSONObject jsonObject = new JSONObject(logistics);
                        String company = jsonObject.getString("company");
                        String number = jsonObject.getString("number");
                        tvLogisticsMessage.setText(number);

                    } catch (Exception e) {

                    }
                } else {
                }
                //查看物流
                btnLogistics.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, AdWebViewActivity.class);
                        intent.putExtra("url", Constants.HOST + "h5/c/payback/logistics"
                                + "?order_id=" + item.getOrder_id());
                        intent.putExtra("title", "查看物流");
                        mContext.startActivity(intent);
                    }

                });
            } else if (status.equals(Constants.PC__ORDER_CANCELLED)) {  /**已取消**/
                helper.setText(R.id.tv_status, "已取消");
                rlBig.setVisibility(View.GONE);
                rlPayment.setVisibility(View.GONE);

            } else {
                helper.setText(R.id.tv_status, "未知");
                rlBig.setVisibility(View.GONE);
            }
        }

        if (item.systemTime == null) item.systemTime = System.currentTimeMillis();
        long time = Long.valueOf(item.diff_time) - (System.currentTimeMillis() - item.systemTime);
        //将前一个缓存
        CountDownTimer countDownTimer;

        countDownTimer = countDownMap.get(item.diff_time);
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (time > 0) {
            countDownTimer = new CountDownTimer(time, 1000) {
                public void onTick(long millisUntilFinished) {
                    leftTime(tvMin, tvSecond, (int) millisUntilFinished / 1000);
                }

                public void onFinish() {
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_ORDER_OPERATION));
                }
            }.start();
            countDownMap.put(item.diff_time, countDownTimer);
        }

    }


    /**
     * 剩余的支付时间
     *
     * @param tvMin
     * @param tvSecond
     * @param diffTime
     */
    private void leftTime(TextView tvMin, TextView tvSecond, int diffTime) {
        if (diffTime <= 0) {
            tvMin.setText("00");
            tvSecond.setText("00");
        } else {
            long min = ((diffTime / (60)));
            long s = (diffTime - min * 60);
            String s_min = min + "";
            if (s_min.length() == 1) {
                s_min = "0" + s_min;
            }
            String s_s = s + "";
            if (s_s.length() == 1) {
                s_s = "0" + s_s;
            }
            tvMin.setText(s_min);
            tvSecond.setText(s_s);
        }
    }

    public void setNewData(List data, Map<String, String> map) {
        setNewData(data);
        this.mUrlMap = map;
    }

    public void addData(List data, Map<String, String> map) {
        addData(data);
        mUrlMap.putAll(map);
    }

    public interface OnClickOrder {
        void cancelClick(String orderId);

        void confirmClick(String orderId);

        void customerClick();

        void goToSubmitOrder(String value, String order_id);
    }
}
